<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use think\Db;
use fast\Random;
use think\Validate;
use app\admin\controller\auth\Admin;
use app\api\controller\Send_wxmessage;
/**
 * 运输公司
 *
 * @icon fa fa-circle-o
 */
class Store extends Backend
{

    /**
     * Store模型对象
     * @var \app\admin\model\Store
     */
    protected $model = null;
    protected $noNeedRight = ['export'];
    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Store;
        $this->view->assign("isJinList", $this->model->getIsJinList());
        $this->view->assign("isDelList", $this->model->getIsDelList());
        $this->view->assign("statusList", $this->model->getStatusList());
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
     /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }

            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $admininfo=$this->auth->getUserInfo();
            $where_admin=['is_del'=>'0'];
            if($admininfo['store_id'])
            {
                $where_admin['pid']=$admininfo['store_id'];
            }
            $list = $this->model
                    ->with(['admin'])
                    ->where($where)
                    ->where($where_admin)
                    ->order($sort, $order)
                    ->paginate($limit);

            foreach ($list as $row) {
                $row->getRelation('admin')->visible(['username','nickname','mobile']);    
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        // $this->view->engine->layout(false);
        return $this->view->fetch();
    }
    /**
     * 编辑
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    // public function edit($ids = null)
    // {
    //     $row = $this->model->get($ids);
    //     if (!$row) {
    //         $this->error(__('No Results were found'));
    //     }
    //     $adminIds = $this->getDataLimitAdminIds();
    //     if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
    //         $this->error(__('You have no permission'));
    //     }
    //     if (false === $this->request->isPost()) {
    //         $row['imagelist']=explode(',',$row['images']);
    //         $this->view->assign('row', $row);
    //         $admininfo=$this->auth->getUserInfo();
    //         $this->assign('admininfo',$admininfo);
    //         $this->assign('store_id',$admininfo['store_id']);
    //         return $this->view->fetch();
    //     }
    //     $params = $this->request->post('row/a');
    //     if (empty($params)) {
    //         $this->error(__('Parameter %s can not be empty', ''));
    //     }
    //     $params = $this->preExcludeFields($params);
    //     $result = false;
    //     Db::startTrans();
    //     try {
    //         //是否采用模型验证
    //         if ($this->modelValidate) {
    //             $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
    //             $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
    //             $row->validateFailException()->validate($validate);
    //         }
    //         // $change_title=$params['change_title'];
    //         // $change_images=$params['change_images'];
    //         // unset($change_title);
    //         // unset($change_images);
            
    //         $result = $row->allowField(true)->update($params);
            
    //         // $result_data['type']='1';
    //         // $result_data['change_id']=$row['id'];
    //         // $result_data['change_title']=$change_title;
    //         // $result_data['change_images']=$change_images;
    //         // $result_data['add_time']=time();
    //         // $change_result=db('change_log')->insert($result_data);
    //         Db::commit();
    //     } catch (ValidateException|PDOException|Exception $e) {
    //         Db::rollback();
    //         $this->error($e->getMessage());
    //     }
    //     if (false === $result) {
    //         $this->error(__('No rows were updated'));
    //     }
    //     $this->success();
    // }

    /**
     * 编辑
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $row['imagelist']=explode(',',$row['images']);
            $this->view->assign('row', $row);
            $admininfo=$this->auth->getUserInfo();
            $this->assign('admininfo',$admininfo);
            $this->assign('store_id',$admininfo['store_id']);
            $change_info=db('change_log')->where(['type'=>'1','change_id'=>$ids])->order('id desc')->find();
            $change_images=[];
            if($change_info)
            {
                $change_images=$change_info['change_images'];
                if($change_images)
                {
                    $change_images=explode(',',$change_images);
                }
            }
            
            $this->assign('change_images',$change_images);
            $this->assign('change_info',$change_info);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }
            $admininfo=$this->auth->getUserInfo();
            $store_id=$admininfo['store_id'];
            
            
            //如果信息是正在审核中的，禁止修改
            if(($row['status']=='1' || $row['status']=='2') && $store_id>0)
            {
                $this->error(__('审核中不可修改', ''));
            }
            $isadd=0;
            if($store_id==0)
            {
                if(isset($params['status'])=='3' && $row['status']=='2')
                {
                    //如果是未通过过，改为已通过过
                    if($row['is_tong']==0)
                    {
                        $params['is_tong']=1;
                        //添加后台登录账号，发送消息
                        $isadd=1;
                    }
                    //通过,如果有申请中的变更记录，需要更改状态
                    $change_info=db('change_log')->where(['type'=>'1','change_id'=>$ids,'status'=>'2'])->find();
                    if(isset($change_info['change_images']) && $change_info['change_images'])
                    {
                        $params['images']=$row['images'].','.$change_info['change_images'];
                    }
                    db('change_log')->where(['id'=>$change_info['id']])->update(['status'=>'3']);
    
                }
                if(isset($params['status'])=='4' && $row['status']=='2')
                {
                    //未通过,如果有申请中的变更记录，需要更改状态
                    $change_info=db('change_log')->where(['type'=>'1','change_id'=>$ids,'status'=>'2'])->find();
                    db('change_log')->where(['id'=>$change_info['id']])->update(['status'=>'4']);
                }
            }
            else
            {
                $params['status']='2';
            }
            
            if(isset($params['change_title']))
            {
                $change_title=$params['change_title'];
                $change_images=$params['change_images'];
                unset($params['change_title']);
                unset($params['change_images']);
                
                $result_data['type']='1';
                $result_data['change_id']=$row['id'];
                $result_data['change_title']=$change_title;
                $result_data['change_images']=$change_images;
                $result_data['add_time']=time();
                $change_result=db('change_log')->insert($result_data);
            }
            
            $result = $row->allowField(true)->save($params);
            if($isadd==1)
            {
                $storeId = $row->id;
             
                $params_admin['username'] = $params['username'];
                $params_admin['password'] = $params['password'];
                $params_admin['nickname'] = $params['store_name'];
                $params_admin['mobile'] = $params['mobile'];
                $params_admin['store_id'] = $storeId;
                $Admin = new Admin;
                $resq = $Admin->addstore($params_admin);
                // var_dump($resq);
                $re=json_decode($resq,true);
                if($re['code']==0)
                {
                    Db::rollback();
                    $this->error($re['msg']);
                }
                
                //发送消息
                
            }
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }
    public function edit_self($ids = null)
    {
        $admininfo=$this->auth->getUserInfo();
        $ids=$admininfo['store_id'];
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $row['imagelist']=explode(',',$row['images']);
            $this->view->assign('row', $row);
            $admininfo=$this->auth->getUserInfo();
            $this->assign('admininfo',$admininfo);
            $this->assign('store_id',$admininfo['store_id']);
            $change_info=db('change_log')->where(['type'=>'1','change_id'=>$ids])->find();
            $change_images=[];
            if($change_info)
            {
                $change_images=$change_info['change_images'];
                if($change_images)
                {
                    $change_images=explode(',',$change_images);
                }
            }
            
            $this->assign('change_images',$change_images);
            $this->assign('change_info',$change_info);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }
            $admininfo=$this->auth->getUserInfo();
            $store_id=$admininfo['store_id'];
            
            
            //如果信息是正在审核中的，禁止修改
            if(($row['status']=='1' || $row['status']=='2') && $store_id>0)
            {
                $this->error(__('审核中不可修改', ''));
            }
            if($store_id==0)
            {
                if($params['status']=='3' && $row['status']=='2')
                {
                    //通过,如果有申请中的变更记录，需要更改状态
                    $change_info=db('change_log')->where(['type'=>'1','change_id'=>$ids,'status'=>'2'])->find();
                    db('change_log')->where(['id'=>$change_info['id']])->update(['status'=>'3']);
    
                }
                if($params['status']=='4' && $row['status']=='2')
                {
                    //未通过,如果有申请中的变更记录，需要更改状态
                    $change_info=db('change_log')->where(['type'=>'1','change_id'=>$ids,'status'=>'2'])->find();
                    db('change_log')->where(['id'=>$change_info['id']])->update(['status'=>'3']);
                }
            }
            else
            {
                $params['status']='2';
            }
            
            if(isset($params['change_title']))
            {
                $change_title=$params['change_title'];
                $change_images=$params['change_images'];
                unset($params['change_title']);
                unset($params['change_images']);
                
                $result_data['type']='1';
                $result_data['change_id']=$row['id'];
                $result_data['change_title']=$change_title;
                $result_data['change_images']=$change_images;
                $result_data['add_time']=time();
                $change_result=db('change_log')->insert($result_data);
            }
            
            $result = $row->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }
    //导出
    public function export()
    {
        $search = $this->request->post('search');
        $ids = $this->request->post('ids');
        $filter = $this->request->post('filter');
        $op = $this->request->post('op');
        $columns = $this->request->post('columns');
        $this->request->get(['search' => $search, 'ids' => $ids, 'filter' => $filter, 'op' => $op]);
        list($where, $sort, $order, $offset, $limit) = $this->buildparams();


       
        $count=$this->model               
                ->where($where)
                ->count();
        // var_dump($count);die;
        $p=$offset/$limit;
        $p=$p+1;
        $list = $this->model            
                ->where($where)
                ->order($sort, $order)
                ->select();
     
   
            vendor('PHPExcel.PHPExcel');
            //添加标题到数组头部
            $file_name = '运输公司列表' . date('Y-m-d_His') . '.xls';
            $PHPExcel = new \PHPExcel();
            // print_r($PHPExcel);die;
            
            $PHPSheet = $PHPExcel->getActiveSheet();
            // 设置A列的宽度为20
            //    $PHPSheet->getColumnDimension('A')->setWidth(30);
           // 设置B列的宽度为30
           $PHPSheet->getColumnDimension('B')->setWidth(30);
           $PHPSheet->getColumnDimension('C')->setWidth(20);
           $PHPSheet->getColumnDimension('D')->setWidth(20);
           $PHPSheet->getColumnDimension('E')->setWidth(20);
           $PHPSheet->getColumnDimension('F')->setWidth(20);
           $PHPSheet->getColumnDimension('G')->setWidth(30);
           $PHPSheet->getColumnDimension('K')->setWidth(30);
           $PHPSheet->getColumnDimension('O')->setWidth(30);
           $PHPSheet->getColumnDimension('P')->setWidth(30);
           $PHPSheet->getColumnDimension('Q')->setWidth(30);
            $PHPSheet->setTitle("表格一");
            
            $PHPSheet->setCellValue("A1", "渣土运输企业及车辆信息统计表");

            $styleArray = array(  
                'alignment' => array(  
                    'horizontal' => \PHPExcel_Style_Alignment::HORIZONTAL_CENTER,  
                    'vertical' => \PHPExcel_Style_Alignment::VERTICAL_CENTER,  
                    'wrap' => true, // 设置自动换行
                ),  
            );  
            $PHPSheet->getStyle('A1')->applyFromArray($styleArray);  
            
            $PHPSheet->mergeCells('A1:Q1');  
            $PHPSheet->setCellValue("A2", "序号");
            $PHPSheet->setCellValue("B2", "企业名称");
            $PHPSheet->setCellValue("C2", "注册地址");
            $PHPSheet->setCellValue("D2", "公司办公地址");
            $PHPSheet->setCellValue("E2", "统一社会信用代码");
            $PHPSheet->setCellValue("F2", "公司成立时间");
            $PHPSheet->setCellValue("G2", "登记机关");
            $PHPSheet->setCellValue("H2", "法人");
            $PHPSheet->setCellValue("I2", "经度");
            $PHPSheet->setCellValue("J2", "纬度");
            $PHPSheet->setCellValue("K2", "地址");
            $PHPSheet->setCellValue("L2", "车辆数量");
            $PHPSheet->setCellValue("M2", "已安装定位及视频装置");
            $PHPSheet->setCellValue("N2", "企业负责人");
            $PHPSheet->setCellValue("O2", "联系电话");
            $PHPSheet->setCellValue("P2", "车辆号牌");
            $PHPSheet->setCellValue("Q2", "带编号车辆号牌");
            $i = 3;
           // dump($res);die;
            foreach ($list as $keys => $value) {    
                $carlist=db('car')->where(['store_id'=>$value['id']])->select();
                $plate_number=[];
                $plate_numbers=[];
                foreach ($carlist as $k => $v) {
                    # code...
                    $plate_number[]=$v['plate_number'];
                    if($v['num'])
                    {
                        $plate_numbers[]=$v['num'].$v['plate_number'];
                    }
                    
                }
                $PHPSheet->setCellValue('A' . $i, '' . $keys+1);
                $PHPSheet->setCellValue('B' . $i, '' . $value['store_name']);
                $PHPSheet->setCellValue('C' . $i, '' . $value['address']);
                $PHPSheet->setCellValue('D' . $i, '' . $value['real_address']);
                $PHPSheet->setCellValue('E' . $i, '' . $value['zz_num']);
                $PHPSheet->setCellValue('F' . $i, '' . $value['establishment_day']);
                $PHPSheet->setCellValue('G' . $i, '' . $value['registration_authority']);
                $PHPSheet->setCellValue('H' . $i, '' . $value['name']);
                $PHPSheet->setCellValue('I' . $i, '' . $value['lng']);
                $PHPSheet->setCellValue('J' . $i, '' . $value['lat']);
                $PHPSheet->setCellValue('K' . $i, '' . $value['real_address']);
                $PHPSheet->setCellValue('L' . $i, '' . $value['car_count']);
                $PHPSheet->setCellValue('M' . $i, '' . $value['install_count']);
                $PHPSheet->setCellValue('N' . $i, '' . $value['contact_name']);
                $PHPSheet->setCellValue('O' . $i, '' . $value['contact_tel']);
                $PHPSheet->setCellValue('P' . $i, '' . implode(',',$plate_number));
                $PHPSheet->setCellValue('Q' . $i, '' . implode(',',$plate_numbers));
                for ($col = 'A'; $col <= 'Q'; $col++) {  
                    // 设置单元格的自动换行样式  
                    $PHPSheet->getStyle($col . $i)->applyFromArray($styleArray); 
                    $PHPSheet->getStyle($col . $i)->applyFromArray($styleArray); 
                }  

                
                $i++;
            }
            for ($col = 'A'; $col <= 'Q'; $col++) {  
                // 设置单元格的自动换行样式  
                $PHPSheet->getStyle($col . 1)->applyFromArray($styleArray); 
                $PHPSheet->getStyle($col . 2)->applyFromArray($styleArray); 
            } 
           
            $PHPWriter = \PHPExcel_IOFactory::createWriter($PHPExcel, "Excel2007");
            header('Content-Disposition: attachment;filename=' . $file_name);
            header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
            $PHPWriter->save("php://output");
   
       
    }
    public function add()
    {
        if (false === $this->request->isPost()) {
            $admininfo=$this->auth->getUserInfo();
            $this->assign('admininfo',$admininfo);
            $this->assign('store_id',$admininfo['store_id']);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);

        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                $this->model->validateFailException()->validate($validate);
            }

            $params['status']=3;
            $params['is_tong']=1;
            $result = $this->model->allowField(true)->save($params);
            $storeId = $this->model->id;
             
            $params_admin['username'] = $params['username'];
            $params_admin['password'] = $params['password'];
            $params_admin['nickname'] = $params['store_name'];
            $params_admin['mobile'] = $params['mobile'];
            $params_admin['store_id'] = $storeId;
            $Admin = new Admin;
            $resq = $Admin->addstore($params_admin);
            // var_dump($resq);
            $re=json_decode($resq,true);
            if($re['code']==0)
            {
                Db::rollback();
                $this->error($re['msg']);
            }
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success();
    }

    //发消息
    function send_message()
    {
        $path='';
        $store_id='';
        $type='';
        $name='';

        
        
        $send = new Send_wxmessage;
        $message['thing2']['value'] = $name;//企业名称
        
        $message['time5']['value'] = date('Y-m-d H:i:s');
        


        $aa=$send->tosendlj($store_id,'qQy_u0br7pGBGjKL8ojPAc7Wyf_qVgOizGYjfPKRJR0',$message,$path,$type);
        return $aa;
    }


}
